iT邦幫忙

2025 iThome 鐵人賽

DAY 10
0
Vue.js

Vue 新手學習紀錄系列 第 10

Day 10|Options API 入門

  • 分享至 

  • xImage
  •  

在 Vue 3 推出之前,Vue 2 只有一種寫法 —— Options API。
它的特色是:用一個物件把所有功能分區塊寫清楚。

  • 資料 → data()
  • 方法 → methods
  • 計算屬性 → computed
  • 監聽 → watch

Options API 基本架構

export default {
  data() {
    return {
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  },
  computed: {
    double() {
      return this.count * 2
    }
  },
  watch: {
    count(newVal, oldVal) {
      console.log(`count 從 ${oldVal} 變成 ${newVal}`)
    }
  }
}

Options API 範例

以搜尋功能為例,能直接用 Options API 管理狀態與計算。

<script>
import posts from '../data/data.js'

export default {
  data() {
    return {
      keyword: '',
      posts
    }
  },
  computed: {
    filteredPosts() {
      if (!this.keyword) return this.posts
      return this.posts.filter(p => 
        p.pSchool.includes(this.keyword) ||
        p.pDep.includes(this.keyword) ||
        p.pResult1.includes(this.keyword)
      )
    }
  }
}
</script>

有哪些優缺點

優點

  • 結構清楚:功能分區塊(data、methods、computed)
  • 對初學友善

缺點

  • 邏輯分散:同一個功能,可能分散在 data、methods、watch 裡
  • 不容易重用邏輯:要抽取邏輯需要 mixin
    也因此才會有 Composition API 的出現,明天打算來看 Composition API 是什麼

上一篇
Day 9|用 vee-validate 做表單驗證
下一篇
Day 11|Composition API 入門
系列文
Vue 新手學習紀錄12
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言